package projeto.piloto;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;

import android.content.Context;
import android.content.res.AssetManager;

public class Anagrams {

	public String[] getSortedAnagrams(Context context, String difficulty) throws FileNotFoundException {
		try{
		    
	    	AssetManager am = context.getAssets();
	    	InputStream is = am.open(difficulty + ".txt");
	    	DataInputStream in = new DataInputStream(is);
			  
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;

			Random randomGenerator = new Random();
			int randomInt = 0;
			
			int fileSize;
			if (difficulty.equals("facil")){
				fileSize = 418;
			}else if (difficulty.equals("medio")) {
				fileSize = 3396;
			}else{
				fileSize = 4737;
			}
			
			while (randomInt == 0 ) {
			    randomInt = randomGenerator.nextInt(fileSize);
			}
			
			int i = 1;
			while (((strLine = br.readLine()) != null) && i != randomInt){
				i++;
			}

			in.close();
			String [] aux = strLine.split(" | ");
			return aux;
			
			  
	
		}catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public ArrayList<String> generateAnagramsList(Context context, String difficulty) throws FileNotFoundException{
		String[] anagramsListIN = getSortedAnagrams(context, difficulty);
				
		int listSize = anagramsListIN.length;
		
		Random randomGenerator = new Random();
		int randomIntAnagram = 0;
		
		while (randomIntAnagram == 0 || anagramsListIN[randomIntAnagram].equals("|")) {
		    randomIntAnagram = randomGenerator.nextInt(listSize);
		}
		
		ArrayList<String> anagramsListOUT = new ArrayList<String>();
		anagramsListOUT.add(anagramsListIN[randomIntAnagram]);
		for (int i = 0; i < anagramsListIN.length; i++){
			if (!(i == randomIntAnagram) && !(anagramsListIN[i].equals("|"))){
				anagramsListOUT.add(anagramsListIN[i]);
			}
		}
		for (int i = 0; i < anagramsListOUT.size(); i++) {
			System.out.println(anagramsListOUT.get(i));
		}
		return anagramsListOUT;		
	}

}